package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.message.param.*;
import com.fzg.common.model.message.result.MessageListResult;
import com.fzg.common.model.message.result.PerMessage;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.Enterprise;
import com.fzg.entity.Message;
import com.fzg.entity.User;
import com.fzg.entity.UserJob;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.MessageMapper;
import com.fzg.mapper.UserJobMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.MessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 留言表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2021-12-13
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private UserJobMapper userJobMapper;

    /**
     * 查询当前登陆的所有消息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper queryAllMessage(QueryAllMessage param) {
        ArrayList<MessageListResult> messageListResults = new ArrayList<>();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){ // 当前登陆的是用户
            // 查询用户的消息列表
            List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                    .eq(Message::getUserAid, user.getAid()));

            for (Message message : messages) {
                MessageListResult messageListResult = new MessageListResult();
                BeanUtils.copyProperties(message,messageListResult);

                Enterprise enterprise = enterpriseMapper.selectById(message.getEnterpriseAid());

                messageListResult.setUserName(user.getName());
                messageListResult.setUserAvatar(user.getAvatar());

                messageListResult.setCompanyName(enterprise.getName());
                messageListResult.setCompanyAvatar(enterprise.getAvatar());

                messageListResults.add(messageListResult);
            }
            return ResponseWrapper.markSuccess(messageListResults);
        }else {
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>().eq(Message::getEnterpriseAid, enterprise.getAid()));

            for (Message message : messages) {
                MessageListResult messageListResult = new MessageListResult();
                BeanUtils.copyProperties(message,messageListResult);

                User user1 = userMapper.selectById(message.getUserAid());

                messageListResult.setUserName(user1.getName());
                messageListResult.setUserAvatar(user1.getAvatar());

                messageListResult.setCompanyName(enterprise.getName());
                messageListResult.setCompanyAvatar(enterprise.getAvatar());
                messageListResults.add(messageListResult);
            }

            return ResponseWrapper.markSuccess(messageListResults);
        }
    }

    /**
     * 得到每个用户或每个公司的消息列表
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getMessageList(QueryAllMessage param) {
        ArrayList<PerMessage> perMessages = new ArrayList<>();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            List<Integer> list = messageMapper.GetComAidOrUserAid(user.getAid());
            for (Integer companyAid : list) {
                PerMessage perMessage = new PerMessage();

                perMessage.setUserAid(user.getAid());
                perMessage.setCompanyAid(companyAid);

                Enterprise enterprise = enterpriseMapper.selectById(companyAid);
                perMessage.setName(enterprise.getName());
                perMessage.setAvatar(enterprise.getAvatar());
                List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                        .eq(Message::getUserAid, user.getAid())
                        .eq(Message::getEnterpriseAid, companyAid)

                );

                if (messages.size() > 1){
                    Message message = messages.get(messages.size() - 1);
                    perMessage.setAid(message.getAid());
                    perMessage.setLastMessage(message.getContent());
                    perMessage.setCreateTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(message.getCreateTime())));
                }else {
                    for (Message message : messages) {
                        perMessage.setAid(message.getAid());
                        perMessage.setLastMessage(message.getContent());
                        perMessage.setCreateTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(message.getCreateTime())));
                    }
                }
                Integer count = 0;
                for (Message message1 : messages) {
                    if (message1.getIsRead().equals(0) && message1.getEnterpriseUser().equals(1)){
                        count++;
                    }
                }
                perMessage.setUnReadCount(count);
                perMessages.add(perMessage);
            }
            return ResponseWrapper.markSuccess(perMessages);
        }else {
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            List<Integer> list = messageMapper.GetUserAid(enterprise.getAid());

            for (Integer userAid : list) {
                PerMessage perMessage = new PerMessage();

                perMessage.setUserAid(userAid);
                perMessage.setCompanyAid(enterprise.getAid());

                User user1 = userMapper.selectById(userAid);
                perMessage.setName(user1.getName());
                perMessage.setAvatar(user1.getAvatar());

                List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                        .eq(Message::getEnterpriseAid, enterprise.getAid())
                        .eq(Message::getUserAid, userAid));

                if (messages.size() > 1){
                    Message message = messages.get(messages.size() - 1);
                    perMessage.setAid(message.getAid());
                    perMessage.setLastMessage(message.getContent());
                    perMessage.setCreateTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(message.getCreateTime())));
                }else {
                    for (Message message : messages) {
                        perMessage.setAid(message.getAid());
                        perMessage.setLastMessage(message.getContent());
                        perMessage.setCreateTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(message.getCreateTime())));
                    }
                }
                Integer count = 0;
                for (Message message1 : messages) {
                    if (message1.getIsRead().equals(0) && message1.getUserEnterprise().equals(1)){
                        count++;
                    }
                }
                perMessage.setUnReadCount(count);
                perMessages.add(perMessage);
            }
            return ResponseWrapper.markSuccess(perMessages);
        }
    }

    /**
     * 打开抽屉将未读消息变为已读
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper changeUnRead(ChangeUnRead param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user!=null){
            Message message = messageMapper.selectById(param.getMessageAid());
            List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                    .eq(Message::getUserAid, user.getAid())
                    .eq(Message::getEnterpriseAid, message.getEnterpriseAid())
                    .eq(Message::getEnterpriseUser, 1));
            for (Message message1 : messages) {
                Message message2 = new Message();
                BeanUtils.copyProperties(message1,message2);
                message2.setIsRead(1);
                messageMapper.updateById(message2);
            }
        }else {
            Message message = messageMapper.selectById(param.getMessageAid());
            List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                    .eq(Message::getUserAid, message.getUserAid())
                    .eq(Message::getEnterpriseAid, message.getEnterpriseAid())
                    .eq(Message::getUserEnterprise, 1));
            for (Message message1 : messages) {
                Message message2 = new Message();
                BeanUtils.copyProperties(message1,message2);
                message2.setIsRead(1);
                messageMapper.updateById(message2);
            }
        }
        return ResponseWrapper.markSuccess();
    }

    /**
     * 根据messageAid和当前登陆人或公司账号查询对应的消息列表
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getMessageByMessageAid(MessageByUserAidAndCompanyAid param) {

        List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getUserAid, param.getUserAid())
                .eq(Message::getEnterpriseAid, param.getCompanyAid()));
        System.out.println("fzg" + messages);
        return ResponseWrapper.markSuccess(messages);

    }

    /**
     * 发送消息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper sendMessage(SendMessageParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){  // 用户给企业发送消息
            Message message = new Message();
            message.setUserAid(user.getAid());
            message.setEnterpriseAid(param.getCompanyAid());
            message.setContent(param.getContent());
            message.setUserEnterprise(1);
            message.setEnterpriseUser(0);
            message.setIsRead(0);
            messageMapper.insert(message);
        }else {
            Message message = new Message();
            message.setUserAid(param.getUserAid());
            message.setEnterpriseAid(param.getCompanyAid());
            message.setContent(param.getContent());
            message.setUserEnterprise(0);
            message.setEnterpriseUser(1);
            message.setIsRead(0);
            messageMapper.insert(message);
        }
        return ResponseWrapper.markSuccess();
    }

    /**
     * 插入一条消息（给公司打招呼）
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper insertMessage(InsertMessage param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));

        // 如果打过招呼
        List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getUserAid, user.getAid())
                .eq(Message::getEnterpriseAid, param.getCompanyAid())
                .eq(Message::getContent, "您好，想了解一下贵公司。"));
        if (messages.size() > 0){
            return ResponseWrapper.markCustomError("已打过招呼，继续沟通吧！");
        }else {
            messageMapper.insert(new Message(){{
                setUserAid(user.getAid());
                setEnterpriseAid(param.getCompanyAid());
                setContent("您好，想了解一下贵公司。");
                setUserEnterprise(1);
                setEnterpriseUser(0);
                setIsRead(0);
            }});
            return ResponseWrapper.markSuccess();
        }
    }

    /**
     * 发送简历（相当于也是发送一条消息）
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper sendResume(SendResume param) {
        User user = userMapper.selectById(param.getUserAid());
        Message message1 = new Message();
        message1.setUserAid(param.getUserAid());
        message1.setEnterpriseAid(param.getCompanyAid());
        if (user.getResumeUrl() != null){
            message1.setContent(user.getResumeUrl());
        }else {
            message1.setContent("http-online-resume");
        }
        message1.setUserEnterprise(1);
        message1.setEnterpriseUser(0);
        message1.setIsRead(0);
        int insert = messageMapper.insert(message1);
        if (insert > 0){
            return ResponseWrapper.markSuccess();
        }else {
            return ResponseWrapper.markError();
        }
    }

    /**
     * 撤回消息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper withdrawApi(WithdrawApi param) {
        int deleteById = messageMapper.deleteById(param.getAid());
        if (deleteById > 0){
            return ResponseWrapper.markCustomSuccess("撤回成功！");
        }else {
            return ResponseWrapper.markCustomError("撤回失败！");
        }
    }

    /**
     * 企业去跟用户沟通（给用户打招呼）
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper companyChatUser(CompanyChatUser param) {

        UserJob userJob = userJobMapper.selectById(param.getUserJobAid());
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));

        int insert = messageMapper.insert(new Message() {{
            setUserAid(userJob.getUseraid());
            setEnterpriseAid(enterprise.getAid());
            setUserEnterprise(0);
            setEnterpriseUser(1);
            setContent("你好，可以发一份你的简历吗？");
            setIsRead(0);
        }});
        if (insert > 0){
            return ResponseWrapper.markSuccess();
        }else {
            return ResponseWrapper.markError();
        }

    }

    /**
     * 判断企业是否与用户沟通过
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper checkIsChart(CompanyChatUser param) {
        UserJob userJob = userJobMapper.selectById(param.getUserJobAid());
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));

        List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getUserAid, userJob.getUseraid())
                .eq(Message::getEnterpriseAid, enterprise.getAid()));
        if (messages.size() > 0){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }

    }
}
